package database;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import rentaldb.Property;

/**
 *
 * @author Pop
 */
public class PropertyDao {
    
    private EntityManager em;
    private EntityManagerFactory emf;
    
    public PropertyDao(){
        try{
            emf = Persistence.createEntityManagerFactory("RentaldbPU");
            em = emf.createEntityManager();  
        }catch(Exception e){ System.out.println(e);}
    }
    
    public void persist(Property prop){
        em.getTransaction().begin();
        em.persist(prop);
        em.getTransaction().commit();
        
    }
    
    public void update(Property prop){
        em.getTransaction().begin();
        em.merge(prop);
        em.getTransaction().commit();
    }
    
    public void delete(Property prop) throws Exception{
        prop = getPropertyById(prop.getPropertyId());
        em.getTransaction().begin();
        em.remove(prop);
        em.getTransaction().commit();
    }
    
    public Property getPropertyById(Integer id) throws Exception{
        //em.createQuery("select * from property");
        Query q = em.createNamedQuery("Property.findByPropertyId");
        q.setParameter("propertyId", id);
        Property prop = (Property)q.getSingleResult();
        
        return prop;
    }
    
    public List<Property> getAllProperties() throws Exception{
        Query q = em.createNamedQuery("Property.findAll");
        List<Property> propList = q.getResultList();
        
        return propList;
    }
}
